import { Injectable } from '@nestjs/common';
import { CreateDesignDto } from './dto/create-design.dto';
import { UpdateDesignDto } from './dto/update-design.dto';
import { InjectRepository } from '@nestjs/typeorm';
import { ADesign } from './entities/design.entity';
import { Repository } from 'typeorm';
import { AView } from './entities/view.entity';
import { AScope } from './entities/scope.entity';
import { AViewScope } from './entities/viewscope.entity';

@Injectable()
export class DesignService {
  constructor(
    @InjectRepository(ADesign)
    private aDesignRepository: Repository<ADesign>,
    @InjectRepository(AView)
    private aViewRepository: Repository<AView>,
    @InjectRepository(AScope)
    private aScopeRepository: Repository<AScope>,
    @InjectRepository(AViewScope)
    private aViewScopeRepository: Repository<AViewScope>,
  ) {}

  async create(createDesignDto: CreateDesignDto) {
    const design = await this.aDesignRepository.save(createDesignDto);
    // const view = new AView();
    // view.design = design;
    // view.name = '视图1';
    // // view.
    // await this.aViewRepository.save(view);
    return design;
  }

  async findAll() {
    const [records, total] = await this.aDesignRepository
      .createQueryBuilder()
      .getManyAndCount();
    return {
      records,
      total,
    };
  }

  async findOne(id: string) {
    const design = await this.aDesignRepository.findOne({
      where: { id },
      relations: [
        'views',
        'scopes',
        'viewscopes',
        'propertys',
        'propertys.scope',
        'viewscopes.view',
        'viewscopes.scope',
      ],
    });

    return design;
  }

  async update(updateDesignDto: UpdateDesignDto) {
    return await this.aDesignRepository.update(
      updateDesignDto.id,
      updateDesignDto,
    );
  }

  async remove(id: string) {
    return await this.aDesignRepository.delete(id);
  }

  /**
   * 保存
   * @param createDesignDto
   */
  async saveAll(dto: CreateDesignDto) {
    for (const view of dto.views) {
      view.design = dto;
    }
    for (const scope of dto.scopes) {
      scope.design = dto;
    }
    for (const property of dto.propertys) {
      property.design = dto;
    }
    await this.aDesignRepository.save(dto);
    await this.aViewRepository.save(dto.views);
    await this.aScopeRepository.save(dto.scopes);
    await this.aScopeRepository.save(dto.viewscopes);
    await this.aScopeRepository.save(dto.propertys);
  }
}
